﻿using UnityEngine;

public class TouchManager : MonoBehaviour
{
    public Transform Ball;
    public float BallDistance = 1;
    public float SpeedFactor = 0.001f;

    private Vector3 lastMousePosition;
    private Rigidbody ballRigid;

    void Start()
    {
        ballRigid = Ball.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        BallUpdate();
        var current = Input.mousePosition;
        var delta = current - lastMousePosition;

        var velocity = delta / Time.deltaTime;

        if (Input.GetMouseButtonUp(0))
        {
            var ballVelocity = Camera.main.transform.forward * velocity.y / 1.414f + 
                                Camera.main.transform.up * velocity.y / 1.414f + 
                                Camera.main.transform.right * velocity.x;

            Debug.Log(ballVelocity);

            ballRigid.isKinematic = false;
            ballRigid.AddForce(ballVelocity * SpeedFactor, ForceMode.Impulse);
        }

        // 记录当前帧光标/触摸的位置，用于下一帧的计算
        lastMousePosition = current;
    }

    void BallUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            ballRigid.isKinematic = true;
            var pos = Input.mousePosition;
            pos.z = BallDistance;
            var worldPos = Camera.main.ScreenToWorldPoint(pos);
            Ball.position = worldPos;
        }
    }
}
